<template>
  <div class="admin">
    <el-container>
      <el-aside width="200">
        <adminHeader></adminHeader>
      </el-aside>
      <el-main>
        <el-page-header content="卡券信息管理"></el-page-header>
        <div style="display: flex;justify-content: space-around">
          <ve-pie :data="byRace" :setting="raceSetting" :style="pieStyle"></ve-pie>
          <ve-pie :data="byType" :setting="raceSetting" :style="pieStyle"></ve-pie>
        </div>
        <div>
          <el-table v-loading="loading"
                    :data="cards" height="81vh"
                    style="background-image: linear-gradient(#ffffff, #f2f6fc);">
            <el-table-column label="卡种" prop="cardrace" align="center" :filters="cardrace" :filter-method="fliterRace"></el-table-column>
            <el-table-column label="卡类" prop="types" align="center" :filters="types" :filter-method="fliterRace"></el-table-column>
            <el-table-column label="面值" prop="price" align="center"></el-table-column>
            <el-table-column label="现价" prop="priceNow" align="center"></el-table-column>
            <el-table-column label="描述" prop="describe" align="center"></el-table-column>
            <el-table-column label="总数" prop="total_num" align="center" sortable></el-table-column>
            <el-table-column fixed="right" align="center">
              <template slot="header">
                <el-button type="primary" icon="el-icon-plus" plain @click="addCard">新增</el-button>
              </template>
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" circle @click="edit(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" circle @click="del(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-dialog title="编辑卡券" :visible.sync="showEdit" @close="close" >
          <el-form ref="sublimForm" :model="sublimForm" size="small" :rules="rules">
            <el-form-item label="卡种" prop="cardrace">
              <el-select v-model="sublimForm.cardrace" allow-create filterable>
                <el-option v-for="item in cardrace" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="卡类" prop="types">
              <el-select v-model="sublimForm.types" allow-create filterable>
                <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="total_num">
              <el-input-number v-model="sublimForm.total_num"></el-input-number>
            </el-form-item>
            <el-form-item label="面值" prop="price">
              <el-radio-group v-model="sublimForm.price">
                <el-radio v-for="(item,index) in prices" :key="index" :label="item"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="现价" prop="priceNow">
              <el-input-number v-model="sublimForm.priceNow"></el-input-number>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="sublimForm.describe"></el-input>
            </el-form-item>
            <el-form-item v-if="changeImg">
              <el-image :src="url"></el-image>
              <el-button type="text" @click="changeImgs">更换图片</el-button>
            </el-form-item>
            <el-form-item v-else>
              <el-upload  ref="upload"
                                      class="upload-demo"
                                      action="#"
                                      :file-list="fileList"
                                      :on-preview="choose"
                                      :auto-upload="false"
                                      :on-remove="removeImg"
                                      list-type="picture">
              <el-button slot="trigger" type="text">选取图片</el-button>
              <el-button type="text" @click="upload">上传</el-button>
            </el-upload>
            </el-form-item>
            <el-form-item align="center">
              <el-button type="primary" @click="submitEdit('sublimForm')">确定</el-button>
              <el-button type="text" @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
        <el-dialog title="新增卡券" :visible.sync="showAdd"  @close="close" >
          <el-form ref="sublimForm" :model="sublimForm" size="small" :rules="rules">
            <el-form-item label="卡种" prop="cardrace">
              <el-select v-model="sublimForm.cardrace" allow-create filterable>
                <el-option v-for="item in cardrace" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="卡类" prop="types">
              <el-select v-model="sublimForm.types" allow-create filterable>
                <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="total_num">
              <el-input-number v-model="sublimForm.total_num"></el-input-number>
            </el-form-item>
            <el-form-item label="面值" prop="price">
              <el-radio-group v-model="sublimForm.price" >
                <el-radio label="5" border size="mini" value="5"></el-radio>
                <el-radio label="10" border size="mini" value="10"></el-radio>
                <el-radio label="20" border size="mini" value="20"></el-radio>
                <el-radio label="50" border size="mini" value="50"></el-radio>
                <el-radio label="100" border size="mini" value="100"></el-radio>
              </el-radio-group>

            </el-form-item>
            <el-form-item label="现价" prop="priceNow">
              <el-input-number v-model="sublimForm.priceNow"></el-input-number>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="sublimForm.describe"></el-input>
            </el-form-item>
            <el-form-item>
              <el-upload  ref="upload"
                          class="upload-demo"
                          action="#"
                          :file-list="fileList"
                          :on-preview="choose"
                          :auto-upload="false"
                          list-type="picture">
                <el-button slot="trigger" type="text">选取图片</el-button>
                <el-button type="text" @click="upload">上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item align="center">
              <el-button type="primary" @click="submitAdd('sublimForm')">新增</el-button>
              <el-button type="text" @click="cancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import adminHeader from "../../components/adminHeader";
export default {
  name: "cardAdmin",
  components:{adminHeader},
  data(){
    return{
      loading:false,
      cards:[],
      showEdit:false,
      form:{},
      types:[],
      sublimForm:{},
      showAdd:false,
      fileList:[],
      base64:'',
      imgurl:'',
      file:{},
      uploadurl:'',
      sha:'',
      cardrace:[],
      height:document.documentElement.clientHeight-120,
      url:'',
      changeImg:true,
      races:[],
      prices:[],
      raceSetting:{
        type:'pie'
      },
      byRace:{
        columns:['cardrace','total_num'],
        rows:[]
      },
      byType:{
        columns:['types','total_num'],
        rows:[]
      },
      pieStyle:{
        width: '400px',
        height: '400px'
      },
      rules:{
        cardrace:[
          {required:true,message:'请输入卡种',trigger:'blur'}
        ],
        types:[
          {required:true,message:'请输入卡类',trigger:'blur'}
        ],
        total_num:[
          {required:true,message:'请输入数量',trigger:'change'}
        ],
        price:[
          {required:true,message:'请输入面值',trigger:'change'}
        ],
        priceNow:[
          {required:true,message:'请输入现价',trigger:'change'}
        ]
      }
    }
  },
  mounted() {
    this.getCard();
  },
  methods:{
    //获取卡券
    getCard(){
      this.loading=true;
      this.axios.get('/api/admin/getCard').then(res=>{
        this.cards = res.data.data;
        console.log(res.data.data);
        var price_arr = [];
        res.data.data.forEach(e=>{
          price_arr.push(e.price)
        });
        this.prices = Array.from(new Set(price_arr));
        console.log(this.prices)
        this.setCardrace();
        this.setTypes();
        console.log(this.cardrace,this.types);
        this.racePie.rows = this.cards;
      }).catch(err=>{
        console.log(err)
      });
      // 通过卡种
      this.axios.get('/api/admin/getCardBy').then(res=>{
        console.log(res.data)
        this.byRace.rows = res.data.byRace;
        this.byType.rows = res.data.byTypes;
      }).catch(err=>{
        console.log(err)
      });
      this.loading = false;
    },

    // 点击修改卡券
    edit(row){
      this.showEdit = true;
      console.log(row);
      this.url = row.url;
      this.sublimForm = row;
      this.fileList = [];
      this.setTypes();
      this.setCardrace();
    },
    changeImgs(){
      this.changeImg = false;
    },
    //新增种类
    setTypes() {
      let types = [];
      var newArr = [];
      console.log(this.cards);
      if (this.cards === undefined){
        this.types = newArr;
      }else {
        for (let i = 0; i < this.cards.length; i++) {
          types.push(this.cards[i].types);
        }
        var arr = [...new Set(types)];
        newArr = arr.map(item => ({label: item, value: item,text:item}));
        this.types = newArr;
      }
    },
    // 新增卡种
    setCardrace() {
      let cardrace = [];
      var newArr = [];
      console.log(this.cards);
      if (this.cards === undefined){
        this.cardrace = newArr;
      }else {
        for (let i = 0; i < this.cards.length; i++) {
          cardrace.push(this.cards[i].cardrace);
        }
        var arr = [...new Set(cardrace)];
        newArr = arr.map(item => ({label: item, value: item,text:item}));
        this.cardrace = newArr;
      }
    },
    // 提交修改
    submitEdit(formName){
      this.$refs[formName].validate(valid=>{
        if (valid){
          this.loading = true;
          this.axios.put('/api/admin/editCard',{
            ...this.sublimForm
          }).then(res=>{
            console.log(res.data.message);
            this.$message.success(res.data.message);
            this.sublimForm = {};
            this.showEdit = false;
            this.changeImg = true;
          }).catch(err=>{
            console.log(err);
            this.$message.error("修改失败");
          });
          this.loading = false;
        }else {
          return false
        }
      })
    },
    // 删除卡券
    del(row){
      console.log(row._id)
      this.loading = true;
      this.axios.delete('/api/admin/delCard',{
        params:{
          _id:row._id
        }
      }).then(res=>{
        console.log(res.data);
        this.$message.success(res.data.message)
      }).catch(err=>{
        console.log(err);
        this.$message.error("删除失败");
      });
      this.getImg();
      this.getCard();
      console.log(row)
    },
    //关闭弹窗
    close(){
      this.getCard();
    },
    //新增卡券
    addCard(){
      this.setTypes();
      this.setCardrace();
      // this.getCardImg();
      this.sublimForm = {};
      this.showAdd = true;
    },
    //提交新增
    submitAdd(formName){
      this.$refs[formName].validate(valid=>{
        if (valid){
          this.loading = true;
          this.axios.post('/api/admin/setCard',{
            ...this.sublimForm,
            url:this.imgurl
          }).then(res=>{
            console.log(res);
            this.$message.success(res.data.message);
            this.sublimForm = {};
            this.showAdd = false;
          }).catch(err=>{
            console.log(err);
          });
        }else {
          return false;
        }
      })

      this.loading = false;
    },
    //点击取消
    cancel(){
      this.sublimForm = {};
      this.fileList=[];
      this.showAdd = false;
      this.showEdit = false
    },
    //选择图片
    choose(file){
      console.log(file);
      this.file = file;
      this.uploadurl = 'https://gitee.com/api/v5/repos/kang-juntao/asset/contents/'+file.name;
      this.file2base(this.file.raw).then(res=>{
        console.log(res);
        this.base64 = res.split('base64,')[1];
        console.log(this.base64);
      });
    },
    //上传图片
    upload(){
      this.axios.post(this.uploadurl,{
        access_token:'93596b68eff4022a12847bda7e92820e',
        content:this.base64,
        message:this.file.name,
        branch:'giftManage'
      }).then(res=>{
        this.sublimForm.url = res.data.content.download_url;
        this.url = this.sublimForm.url;
        this.$refs.upload.submit();
        this.changeImg = true;
        this.base64 = '';
        this.file.name = '';
      }).catch(err=>{
        console.log(err)
      });
    },
    //删除图片
    async removeImg(file){
      var path = file.url.split('anage/')[1];
      var geturl =  "https://gitee.com/api/v5/repos/kang-juntao/asset/contents/" + path;
      var res = this.axios.get(geturl,{
        params:{
          access_token:'93596b68eff4022a12847bda7e92820e',
          ref:'giftManage'
        },
        headers:{
          'Content-Type': 'application/json;charset=utf-8'
        }
      }).then(res=>{
        this.sha = res.data.sha;
        var url = 'https://gitee.com/api/v5/repos/kang-juntao/asset/contents/'+ path;
        this.axios.delete(url,{
          access_token:'93596b68eff4022a12847bda7e92820e',
          sha:this.sha,
          message:"删除",
          branch:'giftManage'
        }).then(res=>{
          console.log(res);
        }).catch(err=>{
          console.log(err)
        })
      });
      console.log(res);
      // var paths =  this.getImg(path);

    },
    // 获取本地图片
    getImg(path){
      console.log(path);
      var geturl =  "https://gitee.com/api/v5/repos/kang-juntao/asset/contents/" + path;
      console.log(geturl);
      var res = this.axios.get(geturl,{
        params:{
          access_token:'93596b68eff4022a12847bda7e92820e',
          ref:'giftManage'
        },
        headers:{
          'Content-Type': 'application/json;charset=utf-8'
        }
      }).then(res=>{
        console.log(res)
        console.log(res.data.sha);
        this.sha = res.data.sha;
        return res.data.sha
      });
      console.log(res)
    },

    fliterRace(value, row, column){
      const property = column['property'];
      return row[property] === value;
    }
  }
}
</script>

<style scoped>
  /*/deep/ .el-dialog__body{*/
  /*  padding: 0 20px;*/
  /*}*/
  /deep/ .el-dialog{
    margin-top: 6vh !important;
    width: 600px;
  }
  /deep/ .el-main{
    margin-top: 10px;
  }
</style>
